/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.async;

import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.util.UserDetails;

import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

public class GssTasks {
	public static final int TASK_NEWFOLDER = 1;
	public static final int TASK_GETFOLDER = 2;
	public static final int TASK_MOVETOTRASH = 3;
	public static final int TASK_DELETE = 4;
	public static final int TASK_UPLOAD = 5;
	public static final int TASK_DOWNLOAD = 6;
	public static final int TASK_GETOTHERS = 7;
	public static final int TASK_GETOTHERUSER = 8;
	public static final int TASK_GETSHARED = 9;
	public static final int TASK_MULTIUPLOAD = 10;
	public static final int TASK_GETHOMEFOLDER = 11;
	public static final int TASK_SEARCH = 12;
	public static final int TASK_PASTE = 12;
	Context context;
	UserDetails details;
	ProgressDialog myprogress;

	public GssTasks(Context context, UserDetails details, ProgressDialog myprogress) {
		this.context = context;
		this.details = details;
		this.myprogress = myprogress;

	}
	
	
	public GssAsyncTask getHomeFolderTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).getFolderResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_GETHOMEFOLDER, result);
				/*
				 * if (result.getResource() != null)
				 * populateList((FolderResource) result.getResource()); else if
				 * (result.getException() != null) handleRestException("TRASH",
				 * result.getException());
				 */
				super.onPostExecute(result);
			}

		};
		return getFolderTask;
	}
	
	public GssAsyncTask getPasteTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Pasting Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				if(params[0].equals("copy"))
					new GssHttpCommands(details).copy(params[1],params[2]);
				else
					new GssHttpCommands(details).move(params[1],params[2]);
				return new RestResource("") {

					@Override
					public String getLastModifiedSince() {
						// TODO Auto-generated method stub
						return null;
					}

					@Override
					public void createFromJSON(String text) throws JSONException {
						// TODO Auto-generated method stub

					}
				};
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_PASTE, result);
				super.onPostExecute(result);
			}

		};
		return getFolderTask;
	}
	
	public GssAsyncTask getFolderTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).getFolderResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_GETFOLDER, result);
				/*
				 * if (result.getResource() != null)
				 * populateList((FolderResource) result.getResource()); else if
				 * (result.getException() != null) handleRestException("TRASH",
				 * result.getException());
				 */
				super.onPostExecute(result);
			}

		};
		return getFolderTask;
	}

	public GssAsyncTask getFileTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				Toast.makeText(context, "Downloading File to /sdcard/gss/", Toast.LENGTH_SHORT).show();
				myprogress = ProgressDialog.show(context, "File Download", "Please Wait", false, false);
				
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				String path = new GssHttpCommands(details).downloadFileCommand(params[0], this);
				
				return new RestResource(path) {

					@Override
					public String getLastModifiedSince() {
						// TODO Auto-generated method stub
						return null;
					}

					@Override
					public void createFromJSON(String text) throws JSONException {
						// TODO Auto-generated method stub

					}
				};
			}
			
			
			@Override
			protected void onProgressUpdate(Integer... values) {
				//myprogress.setTitle(values[0]+"% complete");
				myprogress.setMessage(values[0]+"% complete");
				super.onProgressUpdate(values);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_DOWNLOAD, result);
				/*
				 * if (result.getException() != null)
				 * handleRestException("DOWNLOAD", result.getException()); else
				 * { NotificationManager notificationManager =
				 * (NotificationManager)
				 * getSystemService(Context.NOTIFICATION_SERVICE); long SIMPL =
				 * System.currentTimeMillis(); final Notification notifyDetails
				 * = new Notification(R.drawable.icon, "Pithos Download",
				 * SIMPL); Context context = getApplicationContext();
				 * CharSequence contentTitle = "File " + new
				 * File(result.getResource().getUri()).getName() +
				 * "downloaded..."; CharSequence contentText =
				 * "Open file by clicking me"; Intent notifyIntent = new
				 * Intent(android.content.Intent.ACTION_VIEW, Uri.fromFile(new
				 * File(result.getResource().getUri()))); String ext =
				 * MimeTypeMap
				 * .getSingleton().getFileExtensionFromUrl(result.getResource
				 * ().getUri()); String mime =
				 * MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
				 * 
				 * if (mime != null)
				 * notifyIntent.setDataAndType(Uri.fromFile(new
				 * File(result.getResource().getUri())), mime); PendingIntent
				 * intent = PendingIntent.getActivity(context, 0, notifyIntent,
				 * android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
				 * 
				 * notifyDetails.setLatestEventInfo(context, contentTitle,
				 * contentText, intent); notificationManager.notify(100,
				 * notifyDetails); }
				 */
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}

	public GssAsyncTask getUploadTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Uploading Data", "Please Wait", false, false);

			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				new GssHttpCommands(details).uploadFile(params[0], params[1], this,0);
				return null;

			}
			@Override
			protected void onProgressUpdate(Integer... values) {
				//myprogress.setTitle(values[0]+"% complete");
				myprogress.setMessage(values[0]+"% complete");
				super.onProgressUpdate(values);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_UPLOAD, result);
				/*
				 * if (result.getException() == null)
				 * getFolderTask().execute(currentResource.getUri()); else
				 * handleRestException("UPLOAD", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}
	
	public GssAsyncTask getMultiUploadTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Uploading Data", "Please Wait", false, false);

			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				myprogress.setTitle("Uploading Files "+(params.length/2));
				int j=1;
				for(int i=0;i<params.length;i=i+2){
					
					new GssHttpCommands(details).uploadFile(params[i], params[i+1], this, j);
					j++;
				}
				return null;

			}
			@Override
			protected void onProgressUpdate(Integer... values) {
				//myprogress.setTitle(values[0]+"% complete");
				if(values.length==2){
					myprogress.setMessage("Uploading File "+values[1]+"\n"+values[0]+"% complete");
				}
				else
					myprogress.setMessage(values[0]+"% complete");
				super.onProgressUpdate(values);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_MULTIUPLOAD, result);
				/*
				 * if (result.getException() == null)
				 * getFolderTask().execute(currentResource.getUri()); else
				 * handleRestException("UPLOAD", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}

	public GssAsyncTask deleteFolderTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				new GssHttpCommands(details).deleteFolder(params[0]);
				return null;

			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_DELETE, result);
				/*
				 * if (result.getException() == null)
				 * getFolderTask().execute(currentResource.getUri()); else
				 * handleRestException("DELETE", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}

	public GssAsyncTask trashFolderTask(final GssTaskObserver observer) {
		GssAsyncTask getFolderTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Moving to Trash", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				new GssHttpCommands(details).moveFolderToTrash(params[0]);
				return null;

			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_MOVETOTRASH, result);
				/*
				 * if (result.getException() == null)
				 * getFolderTask().execute(currentResource.getUri()); else
				 * handleRestException("TRASH", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}

	public GssAsyncTask getNewFolderTask(final GssTaskObserver observer) {
		GssAsyncTask task = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Creating Folder", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				new GssHttpCommands(details).createNewFolder(params[0], params[1]);
				return null;

			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_NEWFOLDER, result);
				/*
				 * if (result.getException() == null)
				 * getFolderTask().execute(currentResource.getUri()); else if
				 * (result.getStatusCode() == 409)
				 * showErrorDialog("Duplicate Folder Name",
				 * "A folder with the same name already exists."); else
				 * handleRestException("GET", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return task;
	}

	public GssAsyncTask getOthersTask(final GssTaskObserver observer) {
		GssAsyncTask getTrashTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
				// if(myprogress==null || !myprogress.isShowing()){

				// }
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).getOthersResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_GETOTHERS, result);
				/*
				 * if (result.getResource() != null)
				 * populateList((OthersResource) result.getResource()); else if
				 * (result.getException() != null) handleRestException("TRASH",
				 * result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}

	public GssAsyncTask getOtherUserTask(final GssTaskObserver observer) {
		GssAsyncTask getTrashTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
				// if(myprogress==null || !myprogress.isShowing()){

				// }
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).getOtherUserResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_GETOTHERUSER, result);
				/*
				 * if (result.getResource() != null)
				 * populateList((OtherUserResource) result.getResource()); else
				 * if (result.getException() != null)
				 * handleRestException("TRASH", result.getException());
				 */
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}

	public GssAsyncTask getSharedTask(final GssTaskObserver observer) {
		GssAsyncTask getTrashTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Fetching Data", "Please Wait", true, false);
				// if(myprogress==null || !myprogress.isShowing()){

				// }
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).getSharedResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_GETSHARED, result);
				/*if (result.getResource() != null)
					populateList((SharedResource) result.getResource());
				else if (result.getException() != null)
					handleRestException("TRASH", result.getException());
				*/
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}
	
	public GssAsyncTask getSearchTask(final GssTaskObserver observer) {
		GssAsyncTask searchTask = new GssAsyncTask(details) {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				myprogress = ProgressDialog.show(context, "Searching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(details).search(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				observer.handleResult(TASK_SEARCH, result);
				/*
				 * if (result.getResource() != null)
				 * populateList((FolderResource) result.getResource()); else if
				 * (result.getException() != null) handleRestException("TRASH",
				 * result.getException());
				 */
				super.onPostExecute(result);
			}

		};
		return searchTask;
	}
}
